﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Chowpoo.Common;
using CourseSystem.Common;
using CourseSystem.Common.Helpers;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Entities;
using CourseSystem.Core.Enum;
using CourseSystem.Stat.ActionFilter;
using Webdiyer.WebControls.Mvc;

namespace CourseSystem.Web.Controllers
{
    [UserAuth(UserType = UserTypeEnum.Teacher)]
    public class AdminStudyController : BaseController
    {
        [UrlStatFilter]
        public ActionResult Chapter()
        {
            return View();
        }
        [UrlStatFilter]
        public ActionResult Case()
        {
            return View();
        }


        public ActionResult CaseListUc(int? pid, int type)
        {
            CommonRequest.ClearCache();
            var list = CommonStudyBLL.GetList(type);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        [UploadAuth]
        public ActionResult CaseEdit(int? id)
        {
            if (id.HasValue)
            {
                var info = CommonStudyBLL.Get(id.Value);
                if (info == null)
                    return NotFound();
                return View(info);
            }
            return View(new CommonStudyInfo { Type = 0 });
        }

        [HttpPost]
        [ValidateInput(false)]
        [UploadedAuth]
        public ActionResult CaseEdit(CommonStudyInfo info)
        {
            ViewData.Model = info;
            if (!ModelState.IsValid)
            {
                return View();
            }
            if (info.Id != 0)
            {
                var oldInfo = CommonStudyBLL.Get(info.Id);
                if (oldInfo == null)
                    return View("NotFound");
                oldInfo.Title = info.Title;
                oldInfo.CommonContentInfo.DetailContent = (info.CommonContentInfo.DetailContent ?? "");
                if (CommonContentBLL.Edit(oldInfo.CommonContentInfo) && CommonStudyBLL.Edit(oldInfo))
                {
                    AttachmentsHelper.ClearUselessAttach(oldInfo.CommonContentInfo.DetailContent, ViewData["ranStr"].ToString(), oldInfo.CommonContentId);
                    SetAlertMsg("编辑成功.");
                    return View(oldInfo);
                }
                SetAlertMsg("未知错误.");
                return View();
            }
            info.CommonContentInfo.DetailContent = info.CommonContentInfo.DetailContent ?? "";
            info.AddDate = DateTime.Now;
            info.AddPeop = UserHelper.LoginUser.UserName;
            if (CommonStudyBLL.Add(info))
            {
                AttachmentsHelper.ClearUselessAttach(info.CommonContentInfo.DetailContent, ViewData["ranStr"].ToString(), info.CommonContentId);
                SetAlertMsg("添加成功.", true);
                return View(info);
            }
            SetAlertMsg("未知错误.");
            return View();
        }
        [UrlStatFilter]
        public ActionResult PPT()
        {
            return View();
        }


        public ActionResult PPTListUc(int? pid)
        {
            CommonRequest.ClearCache();
            var list = CommonStudyBLL.GetList(1);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        [UploadAuth]
        public ActionResult PPTEdit(int? id)
        {
            if (id.HasValue)
            {
                var info = CommonStudyBLL.Get(id.Value);
                if (info == null)
                    return NotFound();
                return View(info);
            }
            return View(new CommonStudyInfo { Type = 1 });
        }

        [HttpPost]
        [ValidateInput(false)]
        [UploadedAuth]
        public ActionResult PPTEdit(CommonStudyInfo info)
        {
            var ran = ViewData["ranStr"].ToString();
            ViewData.Model = info;
            if (!ModelState.IsValid)
            {
                return View();
            }
            if (info.Id != 0)
            {
                var oldInfo = CommonStudyBLL.Get(info.Id);
                if (oldInfo == null)
                    return View("NotFound");
                oldInfo.Title = info.Title;
                oldInfo.CommonContentInfo.DetailContent = (info.CommonContentInfo.DetailContent ?? "");
                if (CommonContentBLL.Edit(oldInfo.CommonContentInfo) && CommonStudyBLL.Edit(oldInfo))
                {
                    AttachmentsHelper.ClearUselessAttach(oldInfo.CommonContentInfo.DetailContent, ran, oldInfo.CommonContentId);
                    SetAlertMsg("编辑成功.");
                    return View(oldInfo);
                }
                SetAlertMsg("未知错误.");
                return View();
            }
            info.CommonContentInfo.DetailContent = info.CommonContentInfo.DetailContent ?? "";
            info.AddDate = DateTime.Now;
            info.AddPeop = UserHelper.LoginUser.UserName;
            if (CommonStudyBLL.Add(info))
            {
                AttachmentsHelper.ClearUselessAttach(info.CommonContentInfo.DetailContent, ran, info.CommonContentId);
                SetAlertMsg("添加成功.", true);
                return View(info);
            }
            SetAlertMsg("未知错误.");
            return View();
        }
        [UrlStatFilter]
        public ActionResult Courseware()
        {
            return View();
        }


        public ActionResult CoursewareListUc(int? pid)
        {
            CommonRequest.ClearCache();
            var list = CommonStudyBLL.GetList(2);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult CoursewareEdit(int? id)
        {
            if (id.HasValue)
            {
                var info = CommonStudyBLL.Get(id.Value);
                if (info == null)
                    return NotFound();
                ViewData["FileDic"] = info.CommonContentInfo.DetailContent.Split('/')[0];
                return View(info);
            }
            ViewData["FileDic"] = "";
            return View(new CommonStudyInfo { Type = 2, CommonContentInfo = new CommonContentInfo { } });
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CoursewareEdit(CommonStudyInfo info)
        {
            ViewData["FileDic"] = "";
            ViewData.Model = info;
            if (!ModelState.IsValid)
            {
                return View();
            }
            string msg = "";
            if (info.Id != 0)
            {
                var oldInfo = CommonStudyBLL.Get(info.Id);
                if (oldInfo == null)
                    return View("NotFound");

                var fileDic = oldInfo.CommonContentInfo.DetailContent.Split('/')[0];
                ViewData["FileDic"] = fileDic;
                var fileName = ResourcesHelper.UploadCourseware(Request.Files["UpFile"], fileDic, out msg, false);
                if (!string.IsNullOrEmpty(msg))
                {
                    SetAlertMsg(msg);
                    return View();
                }
                oldInfo.Title = info.Title;
                if (!string.IsNullOrEmpty(fileName))
                    oldInfo.CommonContentInfo.DetailContent = fileName;
                if (CommonContentBLL.Edit(oldInfo.CommonContentInfo) && CommonStudyBLL.Edit(oldInfo))
                {
                    SetAlertMsg("编辑成功.");
                    return View(oldInfo);
                }
                SetAlertMsg("未知错误.");
                return View();
            }
            var fileNameNew = ResourcesHelper.UploadCourseware(Request.Files["UpFile"], "", out msg, true);
            if (!string.IsNullOrEmpty(msg))
            {
                SetAlertMsg(msg);
                return View();
            }
            info.CommonContentInfo = new CommonContentInfo();
            info.CommonContentInfo.DetailContent = fileNameNew;
            info.AddDate = DateTime.Now;
            info.AddPeop = UserHelper.LoginUser.UserName;
            if (CommonStudyBLL.Add(info))
            {
                ViewData["FileDic"] = info.CommonContentInfo.DetailContent.Split('/')[0];
                SetAlertMsg("添加成功.", true);
                return View(info);
            }
            SetAlertMsg("未知错误.");
            return View();
        }


        public ActionResult ChapterListUc(int? pid)
        {
            CommonRequest.ClearCache();
            var list = ChapterBLL.GetList().OrderBy(o => o.OrderId);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }


        public ActionResult SectionListUc(int? pid, int cid)
        {
            CommonRequest.ClearCache();
            var list = SectionBLL.GetList(cid).OrderBy(o => o.OrderId);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        [UploadAuth]
        public ActionResult ChapterEdit(int? id)
        {
            if (id.HasValue)
            {
                var info = ChapterBLL.Get(id.Value);
                if (info == null)
                    return View("NotFound");
                return View(info);
            }
            //(byte)(ChapterBLL.GetMax() + 1)
            return View(new ChapterInfo { OrderId = 0, Name = "" });
        }


        [HttpPost]
        [UploadedAuth]
        [ValidateInput(false)]
        public ActionResult ChapterEdit(ChapterInfo info)
        {
            ViewData.Model = info;
            if (!ModelState.IsValid)
                return PartialView();
            if (info.Id != 0)
            {
                var oldInfo = ChapterBLL.Get(info.Id);
                if (oldInfo == null)
                    return View("NotFound");
                oldInfo.Name = info.Name;
                oldInfo.OrderId = info.OrderId;
                oldInfo.CommonContentInfo.DetailContent = (info.CommonContentInfo.DetailContent ?? "");
                if (CommonContentBLL.Edit(oldInfo.CommonContentInfo) && ChapterBLL.Edit(oldInfo))
                {
                    AttachmentsHelper.ClearUselessAttach(oldInfo.CommonContentInfo.DetailContent, ViewData["ranStr"].ToString(), oldInfo.ContentId);
                    ViewData["AlertMsg"] = "编辑成功.";
                    return View(oldInfo);
                }
                ViewData["AlertMsg"] = "未知错误.";
                return View();
            }
            info.CommonContentInfo.DetailContent = info.CommonContentInfo.DetailContent ?? "";

            if (ChapterBLL.Add(info))
            {
                AttachmentsHelper.ClearUselessAttach(info.CommonContentInfo.DetailContent, ViewData["ranStr"].ToString(), info.ContentId);
                TempData["AlertMsg"] = "添加成功.";
                return RedirectToAction("ChapterEdit", new { id = info.Id, ran = ViewData["ranStr"].ToString() });
            }
            ViewData["Msg"] = "未知错误.";
            return View();
        }


        public ActionResult SectionEdit(int? id, int? cid, string ran)
        {
            ViewData["ranStr"] = ran;
            if (string.IsNullOrEmpty(ran))
            {
                var ranStr = RandomStr.GetByTime(UserHelper.LoginUser.Id + "_" + (byte)UserHelper.LoginUser.UserType + "_");
                ViewData["ranStr"] = ranStr;
                if (string.IsNullOrEmpty(ranStr))
                    return View("NotFound");
            }
            else
            {
                if (!RandomStr.Check(ran))
                    return View("NotFound");
            }
            if (id.HasValue)
            {
                var info = SectionBLL.Get(id.Value);
                if (info == null)
                    return View("NotFound");
                return View(info);
            }
            if (cid.HasValue)
                return View(new SectionInfo { ChapterId = cid.Value, OrderId = (byte)(SectionBLL.GetMax(cid.Value) + 1) });
            return View("NotFound");
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SectionEdit(SectionInfo info, string ran, int cid)
        {
            ViewData["ranStr"] = ran;
            info.ChapterId = cid;
            if (!RandomStr.Check(ran))
                return View("NotFound");
            ViewData.Model = info;
            if (!ModelState.IsValid)
            {
                return View();
            }
            if (info.Id != 0)
            {
                var oldInfo = SectionBLL.Get(info.Id);
                if (oldInfo == null)
                    return View("NotFound");
                oldInfo.Name = info.Name;
                oldInfo.OrderId = info.OrderId;
                oldInfo.CommonContentInfo.DetailContent = (info.CommonContentInfo.DetailContent ?? "");
                if (CommonContentBLL.Edit(oldInfo.CommonContentInfo) && SectionBLL.Edit(oldInfo))
                {
                    //RandomStr.Remove(ran);
                    AttachmentsHelper.ClearUselessAttach(oldInfo.CommonContentInfo.DetailContent, ran, oldInfo.ContentId);
                    ViewData["AlertMsg"] = "编辑成功.";
                    return View(oldInfo);
                }
                ViewData["AlertMsg"] = "未知错误.";
                return View();
            }
            if (cid == 0)
            {
                ViewData["AlertMsg"] = "参数丢失,请重新添加.";
                return View();
            }
            info.CommonContentInfo.DetailContent = info.CommonContentInfo.DetailContent ?? "";
            info.ChapterId = cid;
            if (SectionBLL.Add(info))
            {
                // RandomStr.Remove(ran);
                AttachmentsHelper.ClearUselessAttach(info.CommonContentInfo.DetailContent, ran, info.ContentId);
                TempData["AlertMsg"] = "添加成功.";
                return RedirectToAction("SectionEdit", new { id = info.Id, ran = ran });
            }
            ViewData["AlertMsg"] = "未知错误.";
            return View();
        }

        /// <summary>
        /// 删除3层附件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ChapterDel(int id)
        {
            var info = ChapterBLL.Get(id);
            var toDelList = new List<AttachmentsInfo>();
            //先把关联的附件找到
            foreach (var item in info.SectionInfo)
            {
                toDelList.AddRange(item.CommonContentInfo.AttachmentsInfo);
                //附带信息
                foreach (var item2 in item.CourseStudyInfo)
                {
                    toDelList.AddRange(item2.CommonContentInfo.AttachmentsInfo);
                }
            }
            //确保主体删除后
            if (ChapterBLL.Del(id))
            {
                //删除节自带的测验
                /* foreach(var item in info.SectionInfo)
                 {
                     SectionInfo item1 = item;
                     ExaminationBLL.DelAll(o => o.SectionId == item1.Id);
                 }*/
                ExaminationBLL.DelAll(o => info.SectionInfo.Select(o1 => o1.Id).Contains(o.SectionId));
                //删除附件
                AttachmentsBLL.DelFileByList(toDelList);
                TempData["AlertMsg"] = "删除成功.";
            }
            return RedirectToAction("Chapter");
        }

        public ActionResult CommonStudyDel(int id)
        {
            var info = CommonStudyBLL.Get(id);
            if (info == null)
                return NotFound();
            int type = info.Type;
            //自身
            var toDelList = info.CommonContentInfo.AttachmentsInfo.ToList();
            if (CommonStudyBLL.Del(id))
            {
                if (info.Type == 2)
                {
                    var fileDic = info.CommonContentInfo.DetailContent.Split('/')[0];
                    System.IO.Directory.Delete(Server.MapPath("~/") + "Upload/Courseware/" + fileDic, true);
                }
                else
                    AttachmentsBLL.DelFileByList(toDelList);
                SetAlertMsg("删除成功.", true);
            }
            switch (type)
            {
                case 0: return RedirectToAction("Case"); break;
                case 1: return RedirectToAction("PPT"); break;
                case 2: return RedirectToAction("Courseware"); break;
                case 3: return RedirectToAction("Prospect"); break;
                default: return RedirectToAction("Case"); break;
            }
        }

        /// <summary>
        /// 除了自身的信息要删除,还要删除附带的信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cid"></param>
        /// <returns></returns>
        public ActionResult SectionDel(int id, int cid)
        {
            var info = SectionBLL.Get(id);
            if (info == null)
                return NotFound();
            //自身
            var toDelList = info.CommonContentInfo.AttachmentsInfo.ToList();
            //附带信息
            foreach (var item in info.CourseStudyInfo)
            {
                toDelList.AddRange(item.CommonContentInfo.AttachmentsInfo);
            }
            if (SectionBLL.Del(id) && ExaminationBLL.DelAll(o => o.SectionId == id))
            {
                AttachmentsBLL.DelFileByList(toDelList);
                SetAlertMsg("删除成功.", true);
            }
            return RedirectToAction("Section", new { cid });
        }


        public ActionResult Section(int? cid)
        {
            if (!cid.HasValue)
                return View("NotFound");
            var info = ChapterBLL.Get(cid.Value);
            if (info == null)
                return View("NotFound");
            return View(info);
        }


        public ActionResult StudyEdit(int cid, byte ty, string ran)
        {
            ViewData["ranStr"] = ran;
            if (string.IsNullOrEmpty(ran))
            {
                var ranStr = RandomStr.GetByTime(UserHelper.LoginUser.Id + "_" + (byte)UserHelper.LoginUser.UserType + "_");
                ViewData["ranStr"] = ranStr;
                if (string.IsNullOrEmpty(ranStr))
                    return View("NotFound");
            }
            else
            {
                if (!RandomStr.Check(ran))
                    return View("NotFound");
            }
            //检验合法性
            var test = (CourseStudyMenuEnum)ty;
            var sectionInfo = SectionBLL.Get(cid);
            if (sectionInfo == null)
            {
                return View("NotFound");
            }
            var info = CourseStudyBLL.Get(cid, ty);
            if (info == null)
            {
                info = new CourseStudyInfo
                                  {
                                      SectionId = cid,
                                      Type = ty,
                                      CommonContentInfo = new CommonContentInfo { DetailContent = "" }
                                  };
                if (!CourseStudyBLL.Add(info))
                {
                    return View("NotFound");
                }
            }
            return View(info);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult StudyEdit(CourseStudyInfo info, string ran)
        {
            ViewData["ranStr"] = ran;
            if (!RandomStr.Check(ran))
                return View("NotFound");
            ViewData.Model = info;
            if (!ModelState.IsValid)
                return View();
            if (info.Id != 0)
            {
                var oldInfo = CourseStudyBLL.Get(info.Id);
                if (oldInfo == null)
                    return View("NotFound");
                oldInfo.CommonContentInfo.DetailContent = (info.CommonContentInfo.DetailContent ?? "");
                if (CommonContentBLL.Edit(oldInfo.CommonContentInfo))
                {
                    //RandomStr.Remove(ran);
                    AttachmentsHelper.ClearUselessAttach(oldInfo.CommonContentInfo.DetailContent, ran, oldInfo.ContentId);
                    ViewData["AlertMsg"] = "编辑成功.";
                    return View(oldInfo);
                }
                SetAlertMsg("未知错误.");
                return View();
            }
            return View("NotFound");
        }
        [UrlStatFilter]
        public ActionResult Internet()
        {
            return View();
        }

        public ActionResult InternetListUc(int? pid)
        {
            CommonRequest.ClearCache();
            var list = InternetResourcesBLL.GetList().OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult InternetEditUc(int? id)
        {
            if (id.HasValue)
            {
                var info = InternetResourcesBLL.Get(id.Value);
                if (info == null)
                    return NotFound();
                return PartialView(info);
            }
            return PartialView(new InternetResourcesInfo { });
        }

        [HttpPost]
        public ActionResult InternetEditUc(InternetResourcesInfo info)
        {
            ViewData.Model = info;
            if (!ModelState.IsValid)
                return PartialView();
            info.Remark = info.Remark ?? "";
            if (info.Id != 0)
            {
                var oldInfo = InternetResourcesBLL.Get(info.Id);
                if (oldInfo == null)
                    return NotFound();
                oldInfo.Name = info.Name;
                oldInfo.Link = info.Link;
                oldInfo.Remark = info.Remark ?? "";
                if (InternetResourcesBLL.Edit(oldInfo))
                {
                    SetHighLineMsg("编辑成功.");
                    return PartialView(oldInfo);
                }
                SetHighLineMsg("未知错误.");
                return PartialView();
            }
            if (InternetResourcesBLL.Add(info))
            {

                SetHighLineMsg("编辑成功.");
                return PartialView();
            }
            SetHighLineMsg("未知错误.");
            return PartialView();
        }

        public ActionResult InternetDel(int id)
        {
            if (InternetResourcesBLL.Del(id))
                SetAlertMsg("删除成功.");
            return RedirectToAction("Internet");
        }
        [UrlStatFilter]
        public ActionResult Prospect()
        {
            return View();
        }



        [UploadAuth]
        public ActionResult ProspectEdit(int? id)
        {
            if (id.HasValue)
            {
                var info = CommonStudyBLL.Get(id.Value);
                if (info == null)
                    return NotFound();
                return View(info);
            }
            return View(new CommonStudyInfo { Type = 3 });
        }

        [HttpPost]
        [ValidateInput(false)]
        [UploadedAuth]
        public ActionResult ProspectEdit(CommonStudyInfo info)
        {
            ViewData.Model = info;
            if (!ModelState.IsValid)
            {
                return View();
            }
            if (info.Id != 0)
            {
                var oldInfo = CommonStudyBLL.Get(info.Id);
                if (oldInfo == null)
                    return View("NotFound");
                oldInfo.Title = info.Title;
                oldInfo.CommonContentInfo.DetailContent = (info.CommonContentInfo.DetailContent ?? "");
                if (CommonContentBLL.Edit(oldInfo.CommonContentInfo) && CommonStudyBLL.Edit(oldInfo))
                {
                    AttachmentsHelper.ClearUselessAttach(oldInfo.CommonContentInfo.DetailContent, ViewData["ranStr"].ToString(), oldInfo.CommonContentId);
                    SetAlertMsg("编辑成功.");
                    return View(oldInfo);
                }
                SetAlertMsg("未知错误.");
                return View();
            }
            info.CommonContentInfo.DetailContent = info.CommonContentInfo.DetailContent ?? "";
            info.AddDate = DateTime.Now;
            info.AddPeop = UserHelper.LoginUser.UserName;
            if (CommonStudyBLL.Add(info))
            {
                AttachmentsHelper.ClearUselessAttach(info.CommonContentInfo.DetailContent, ViewData["ranStr"].ToString(), info.CommonContentId);
                SetAlertMsg("添加成功.", true);
                return View(info);
            }
            SetAlertMsg("未知错误.");
            return View();
        }
        public ActionResult ProspectListUc(int? pid, int type)
        {
            CommonRequest.ClearCache();
            var list = CommonStudyBLL.GetList(type);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

    }
}
